﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Autodesk.Revit.DB;

namespace YArchitech.Revit
{
	public sealed class HYTwinkle : IDisposable
	{
		public int TwinkleInterval { get; set; }

		public View View { get; set; }

		public ICollection<ElementId> Ids { get; set; }

		public void Dispose()
		{
			this.Stop();
			if (this.twinkleTimer != null)
			{
				this.twinkleTimer.Dispose();
			}
		}

		public HYTwinkle()
		{
			this.TwinkleInterval = 300;
			this.twinkleTimer = new Timer();
			this.twinkleTimer.Tick += this.OnTick;
		}

		public bool Start()
		{
			if (this.Ids == null || this.Ids.Count == 0)
			{
				return false;
			}
			this.twinkleTimer.Interval = this.TwinkleInterval;
			this.twinkleTimer.Start();
			return true;
		}

		public void Stop()
		{
			this.twinkleTimer.Stop();
			this.UnHide();
		}

		private void OnTick(object sender, EventArgs e)
		{
			if (!this.hide)
			{
				this.Hide();
				return;
			}
			this.UnHide();
		}

		private void Hide()
		{
			if (this.Ids == null || this.Ids.Count == 0 || this.hide)
			{
				return;
			}
			try
			{
				Transaction transaction = new Transaction(this.View.Document, "HYTwinkle Hide");
				transaction.Start();
				this.View.HideElements(this.Ids);
				transaction.Commit();
				this.hide = true;
			}
			catch
			{
			}
		}

		private void UnHide()
		{
			if (this.Ids == null || this.Ids.Count == 0 || !this.hide)
			{
				return;
			}
			try
			{
				Transaction transaction = new Transaction(this.View.Document, "HYTwinkle UnHide");
				transaction.Start();
				this.View.UnhideElements(this.Ids);
				transaction.Commit();
				this.hide = false;
			}
			catch
			{
			}
		}

		private Timer twinkleTimer;

		private bool hide;
	}
}
